<template>
  <div class="container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-form-item label="题目" prop="question">
          <el-input v-model="filters.question" placeholder="题目内容" clearable></el-input>
        </el-form-item>
        <el-form-item label="学期" prop="termId">
          <el-select v-model="filters.termId" placeholder="请选择" clearable>
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <kt-button :label="$t('action.search')" perms="sys:psyQuestion:view" type="primary" @click="findPage(null)"/>
        </el-form-item>
        <el-form-item>
          <kt-button :label="$t('action.add')" perms="sys:psyQuestion:add" type="primary" @click="handleAdd" />
        </el-form-item>
        <el-form-item>
          <kt-button :label="$t('action.import')" perms="sys:psyQuestion:import" type="primary" @click="handleImport" />
        </el-form-item>
      </el-form>
    </div>
    <!--表格内容栏-->
    <kt-table permsEdit="sys:psyQuestion:edit" permsView="sys:psyQuestion:view" 
              permsDelete="sys:psyQuestion:delete" :data="pageResult" :columns="columns" 
              @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
    </kt-table>
    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="40%" :visible.sync="editDialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size">
        <el-form-item label="题目" prop="question">
          <el-input type="textarea" :rows="3" v-model="dataForm.question" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="学期" prop="termId">
          <el-select v-model="dataForm.termId" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序号" prop="sortNum">
          <el-input-number v-model="dataForm.sortNum" :min="1" :max="10" :step="1"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="editDialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>
    <!-- 导入题目弹框，选择学期 -->
    <el-dialog
      class="login-resetPwd"
      title="导入题目"
      :visible.sync="importDialogVisible"
      width="30%">
      <el-form :model="importInline" ref="importInline" label-position="left" label-width="100px" class="demo-ruleForm login-container">
        <el-form-item label="学期" prop="termId">
          <el-select v-model="importInline.termId" placeholder="请选择" style="width: 100%;">
            <el-option
              v-for="item in termOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件名称" class="file-line" prop="fileName">
          <el-input :readonly="true" v-model="importInline.fileName" placeholder="文件名称"></el-input>
          <el-upload
            style="display: inline-block;margin: 0 10px"
            action="string"
            :show-file-list="false"
            :http-request="uploadImgImport"
            :before-upload="beforeFirstAvatarUploadexcel"
            title="导入">
            <el-button type="primary" class="tableBtn">选择文件</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="importFile">导 入</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import KtTable from "@/views/Core/KtTable"
import KtButton from "@/views/Core/KtButton"
import { format } from "@/utils/datetime"

export default {
  components:{
    KtTable,
    KtButton
  },
  data() {
    return {
      size: 'small',
      filters: {
        question: '',
        termId: ''
      },
      columns: [
        {prop:"question", label:"题目内容", minWidth:250},
        {prop:"sortNum", label:"排序号", minWidth:100},
        {prop:"termName", label:"学期", minWidth:150},
        {prop:"createBy", label:"创建人", minWidth:100},
        {prop:"createTime", label:"创建时间", minWidth:150, formatter: this.dateFormat}
      ],
      pageRequest: { pageNum: 1, pageSize: 8 },
      pageResult: {},
      operation: false, // true:新增, false:编辑
      editDialogVisible: false, // 新增编辑界面是否显示
      editLoading: false,
      dataFormRules: {
        question: [
          { required: true, message: '请输入题目内容', trigger: 'blur' }
        ],
        termId: [
          { required: true, message: '请选择学期', trigger: 'change' }
        ]
      },
      // 新增编辑界面数据
      dataForm: {
        id: null,
        question: null,
        termId: null,
        sortNum: 1
      },
      termOptions: [],
      importDialogVisible: false,
      importInline: {
        termId: null,
        fileName: null
      },
      itemFile: {} // 保存上传文件流
    }
  },
  methods: {
    // 分页查询
    findPage: function (data) {
      // 确保params是一个对象
      let params = data || {};
      
      // 如果传入了pageRequest，使用传入的值更新本地的pageRequest
      if (data && data.pageRequest) {
        this.pageRequest = data.pageRequest;
      }
      
      // 构建请求参数
      let requestParams = {
        pageNum: this.pageRequest.pageNum,
        pageSize: this.pageRequest.pageSize,
        params: []
      };
      
      // 添加过滤条件
      if (this.filters.question) {
        requestParams.params.push({
          name: 'question', 
          value: '%' + this.filters.question + '%'
        });
      }
      
      if (this.filters.termId) {
        requestParams.params.push({
          name: 'termId',
          value: this.filters.termId
        });
      }
      
      // 添加调试信息
      console.log('开始调用findPage方法');
      console.log('请求参数:', requestParams);
      
      // 调用API
      try {
        this.$api.psyQuestion.findPage(requestParams).then(res => {
          this.pageResult = res.data;
          if (data && data.callback) {
            data.callback();
          }
        }).catch(error => {
          console.error('API调用出错:', error);
          this.$message.error('获取数据失败：' + (error.message || '未知错误'));
          if (data && data.callback) {
            data.callback();
          }
        });
      } catch (error) {
        console.error('调用findPage出错:', error);
        this.$message.error('获取数据失败，请检查控制台错误信息');
        if (data && data.callback) {
          data.callback();
        }
      }
    },
    // 批量删除
    handleDelete: function (data) {
      this.$api.psyQuestion.batchDelete(data.params).then(res => {
        if (data && data.callback) {
          data.callback();
        }
      }).catch(error => {
        console.error('删除失败:', error);
        this.$message.error('删除失败：' + (error.message || '未知错误'));
        if (data && data.callback) {
          data.callback();
        }
      });
    },
    // 显示新增界面
    handleAdd: function () {
      this.editDialogVisible = true
      this.operation = true
      this.dataForm = {
        id: null,
        question: null,
        termId: null,
        sortNum: 1
      }
    },
    // 显示编辑界面
    handleEdit: function (params) {
      this.editDialogVisible = true
      this.operation = false
      this.dataForm = Object.assign({}, params.row)
    },
    // 编辑
    submitForm: function () {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            let params = Object.assign({}, this.dataForm)
            this.$api.psyQuestion.save(params).then((res) => {
              if(res.code == 200) {
                this.$message({ message: '操作成功', type: 'success' })
              } else {
                this.$message({message: '操作失败, ' + res.msg, type: 'error'})
              }
              this.editLoading = false
              this.$refs['dataForm'].resetFields()
              this.editDialogVisible = false
              this.findPage(null)
            })
          })
        }
      })
    },
    // 时间格式化
    dateFormat: function (row, column, cellValue, index){
      return format(row[column.property])
    },
    // 获取学期下拉框选项
    getTermOptions: function (){
      this.$api.busTerm.findOptions(0).then(res => {
        this.termOptions = res.data
      })
    },
    // 显示导入对话框
    handleImport(){
      this.importDialogVisible = true
    },
    // 上传文件
    uploadImgImport(item) {
      this.itemFile = item.file
    },
    // 导入事件前置处理
    beforeFirstAvatarUploadexcel(file) {
      let termId = this.importInline.termId
      if (!termId) {
        this.$message.error('请选择导入的学期')
      }
      const isEXECL = file.type === `application/vnd.ms-excel` || file.type === `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
      if (!isEXECL) {
        this.$message.error('请导入正确的格式')
      }
      if (termId && isEXECL) {
        this.importInline.fileName = file.name
      }
      return termId && isEXECL
    },
    // 导入文件
    importFile(){
      let formData = new FormData()
      formData.append('file', this.itemFile)
      formData.append('termId', this.importInline.termId)
      this.$api.psyQuestion.importQuestions(formData).then(res => {
        if(res.code == 200) {
          this.$message({ message: res.msg, type: 'success' })
        } else {
          this.$message({message: '操作失败, ' + res.msg, type: 'error'})
        }
        this.importDialogVisible = false
        this.findPage(null)
      })
    }
  },
  mounted() {
    this.getTermOptions()
    this.findPage(null)
  }
}
</script>

<style scoped>
</style> 